import {
  CozeAPI,
  COZE_CN_BASE_URL,
  getPKCEAuthenticationUrl,
  getPKCEOAuthToken,
  refreshOAuthToken,
} from "@coze/api";
const clientId = "49053446382117412308585919527867.app.coze";
// const redirectUrl = "http://localhost:3000";
const redirectUrl = "https://jishuba.cn/idea-canvas/";
const baseURL = COZE_CN_BASE_URL;

class CozeClient {
  static instance = null;
  constructor() {
    if (CozeClient.instance) {
      return CozeClient.instance;
    }
    this.data = {}
    CozeClient.instance = this;
  }

  getAuthCode = async () => {
    if(this.client) {
        return
    }
    // Generate the PKCE authentication URL and code verifier
    const { url, codeVerifier } = await getPKCEAuthenticationUrl({
      clientId,
      redirectUrl,
      baseURL,
      state: "123", // Set a state parameter for user data
    });
    console.log("getAuthCode", url, codeVerifier);
    localStorage.setItem('codeVerifier', codeVerifier);
    window.location.href = url;
  };

  initCozeClientWithoutCode = async () => {
    const url = window.location.href;
    const code = cozeClient.getCodeFromUrl(url);
    if (code) {
      this.initCozeClient({ code });
    }
  }

  initCozeClient = async ({ code }) => {
    const codeVerifier = localStorage.getItem('codeVerifier');
    // console.log("initCozeClient using code", code);
    let oauthToken = JSON.parse(localStorage.getItem('oauthToken'));
    if(!oauthToken) {
        oauthToken = await getPKCEOAuthToken({
        clientId,
        redirectUrl,
        baseURL,
        code, 
        codeVerifier: codeVerifier,
        });
        localStorage.setItem('oauthToken', JSON.stringify(oauthToken));
    }
    // Initialize a new Coze API client using the obtained access token
    const client = new CozeAPI({
      baseURL,
      token: async () => {
        // Refresh the OAuth token using the refresh token obtained earlier
        if (oauthToken.expires_in * 1000 > Date.now() + 5000) {
          return oauthToken.access_token;
        }
        console.log('refresh token');
        const refreshTokenResult = await refreshOAuthToken({
          clientId,
          refreshToken: oauthToken.refresh_token,
          baseURL,
        });
        oauthToken = refreshTokenResult;
        localStorage.setItem('oauthToken', JSON.stringify(oauthToken));
        return oauthToken.access_token;
      },
    });
    this.client = client;
    this.oauthToken = oauthToken;
  };

  refreshCozeClient = async () => {
    // Refresh the OAuth token using the refresh token obtained earlier
    const refreshedOAuthToken = await refreshOAuthToken({
      clientId,
      refreshToken: this.oauthToken.refresh_token,
      baseURL,
    });
  };

  getCodeFromUrl = () => {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get("code");
  };
}
const cozeClient = new CozeClient();
export default cozeClient;
